let Socket = ''
let setIntervalWesocketPush = null
var Lxcachemsgs = [] //离线消息
let scoketurl = 'wss://scoket.xiaoshagua.top:5000'
//let scoketurl = 'ws://127.0.1:5000'
/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = url => {
	Socket && Socket.close()
	if (!Socket) {
		
		console.log('开始建立websocket连接')
		Socket = new WebSocket(url)
		Socket.onopen = onopenWS //建立连接之后引发的事件称为 onopen
		Socket.onmessage = onmessageWS
		Socket.onerror = onerrorWS
		Socket.onclose = oncloseWS
	} else {
		console.log('websocket已连接-66666')
		
	}
}

/**打开WS之后发送心跳 */
const onopenWS = () => {
	console.log('心跳监测 ');
	localStorage.setItem('lost_connection',true)
	if (localStorage.getItem('cacheLoginUserName') != null) {
		sendPing()
		Socket.send(JSON.stringify({
			Msgs: localStorage.getItem('cacheLoginUserName'),
			userimgurl:localStorage.getItem("cacheLoginUserImg"),
			useruuid:localStorage.getItem("cacheLoginuuid"),
			MsgType: 0
		}))

		Lxcachemsgs.forEach(r => {
			Socket.send(JSON.stringify(r))
		})
	}
}

/**连接失败重连 */
const onerrorWS = () => {
	Socket.close()
	clearInterval(setIntervalWesocketPush)
	console.warn('连接失败重连中')

	localStorage.removeItem('lost_connection')

	window.dispatchEvent(new CustomEvent('onlost_connection', {
		detail: {
			data: false
		}
	}))

	if (Socket && Socket.readyState !== 3) {
		Socket = null
		createSocket(scoketurl)
	}
}

/**断开重连 */
const oncloseWS = () => {
	clearInterval(setIntervalWesocketPush)
	console.warn('websocket已断开....正在尝试重连')
	if (Socket && Socket.readyState !== 2) {
		Socket = null
		createSocket(scoketurl)
	}
}

/**WS数据接收统一处理 */
const  onmessageWS = e => {
	//console.log(e)
	let objmsg = JSON.parse(e.data)

	if (objmsg.msgType == 2) //视频通话
	{
		window.dispatchEvent(new CustomEvent('OnKKRTC', {
			detail: {
				data: objmsg
			}
		}))
	}
	window.dispatchEvent(new CustomEvent('onmessageWS', {
		detail: {
			data: e.data
		}
	}))
}




/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据 (递归发送离线消息---》消息是反的)
 */
const connecting = message => {
	setTimeout(() => {
		if (Socket.readyState === 0) { //正在建立连接连接，还没有完成
			connecting(message)
		} else {
			alert(message.msgs)
			Socket.send(JSON.stringify(message))
		}
	}, 1000)
}


/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = message => {
	//console.info(message)
	//console.info(Socket.readyState)

	if (Socket.readyState === 3) {
		//cachemsgs.push(message)
		Socket.close()
		createSocket(scoketurl)
	} else if (Socket.readyState === 1) {
		Socket.send(JSON.stringify(message))
	} else if (Socket.readyState === 0) { //重连中  本地缓存未发送的消息
		//connecting(message)
		Lxcachemsgs.push(message)
	}
}


/**发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (time = 7000, ping = 'Ping') => {
	clearInterval(setIntervalWesocketPush)
	//Socket.send(ping)
	setIntervalWesocketPush = setInterval(() => {
		try {
			Socket.send(ping)
			//console.log('健康')
		} catch (e) {
			console.warn('重连中...')
			oncloseWS()


		}
	}, time)
}

//详情
//https://www.jianshu.com/p/938004c22ed9
